package com.portal.framework.page;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.portal.framework.common.lang.Caster;
import com.portal.framework.util.CollectionUtils;

/**
 * 
 * @author chenxingji
 * 
 */
public class PagerResult<T> {

	public PagerResult() {
	}

	public PagerResult(List<T> result, Pager pager) {
		this.result = result;
		this.pager = pager;
	}

	// 结果列表
	private List<T> result;

	// 结果分页器

	private Pager pager;

	public Pager getPager() {
		return pager;
	}

	public void setPager(Pager pager) {
		this.pager = pager;
	}

	public List<T> getResult() {
		return result;
	}

	public void setResult(List<T> result) {
		this.result = result;
	}

	public void setResult(List resultList, Class<? extends T> cls) {

		this.result = new ArrayList<T>();
		if (resultList == null)
			return;
		for (Object obj : resultList) {
			result.add(cls.cast(obj));
		}
	}

	public void setResult(Iterator resultList, Class<? extends T> cls) {
		this.result = new ArrayList<T>();
		if (resultList == null)
			return;
		while (resultList.hasNext()) {
			result.add(cls.cast(resultList.next()));
		}
	}

	/**
	 * 设置结果列表和分类器
	 * 
	 * @param result
	 * @param pager
	 */
	public void create(List<T> result, Pager pager) {
		this.result = result;
		this.pager = pager;
	}

	public void create(List resultList, Pager pager, Class<T> cls) {
		setResult(resultList, cls);
		this.pager = pager;
	}
	
	/**
	 * 转换成一个新的类型的PagerResult
	 * 
	 * @param <V>
	 * @param cls
	 *            新的类型
	 * @return
	 */
	public <V> PagerResult<V> cast(Class<V> cls) {
		PagerResult<V> r = new PagerResult<V>();
		r.setPager(pager);
		r.setResult(this.result, cls);
		return r;
	}

	/**
	 * 根据类型转换器转换对象
	 * 
	 * @param <V>
	 * @param co
	 * @return
	 */
	public <V> PagerResult<V> cast(Caster<V> co) {
		PagerResult<V> r = new PagerResult<V>();
		r.setPager(pager);
		r.setResult(CollectionUtils.toList(this.result.iterator(), co));
		return r;
	}

}
